package cn.youruan.demo.controller;


import cn.youruan.demo.common.R;
import cn.youruan.demo.domain.Log;
import cn.youruan.demo.domain.User;
import cn.youruan.demo.dto.UserDto;
import cn.youruan.demo.service.ILogService;
import cn.youruan.demo.service.IUserService;
import cn.youruan.demo.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ILogService logService;

    /**
     * 用户手机号注册
     * @param userDto
     * @param session
     * @return
     */
    @PostMapping("/register")
    public R<String> login(@RequestBody UserDto userDto, HttpSession session) {
        //1.获取手机号
        String phone = userDto.getPhone();
        AssertUtils.hasText(phone, "手机号不能为空!!!");

        //2.获取用户输入密码
        String password = userDto.getPassword();
        AssertUtils.hasText(password, "密码不能为空!!!");

        //2.获取验证码
        String code = userDto.getCode();
        AssertUtils.hasText(code, "验证码不能为空!!!");

        //3.从session里面获取验证码
        String phoneCode = (String) session.getAttribute(phone);
        //4.比对验证码
        if (phoneCode !=null && phoneCode.equals(code)) {
            //5.如果是新用户,则需要保存到数据库里面
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setPassword(password);
                userService.save(user);
                return  R.success("注册成功!!!");
            }else {
                return  R.error("该用户已经注册!!!");
            }
        }
        return  R.error("验证码输入有误,请重新输入!!!");
    }

    /**
     * 发送手机验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //1.获取手机号
        String phone = user.getPhone();
        //判断手机号是否为空
        if (StringUtils.isNotEmpty(phone)) {
            //2.生成4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //3.调用短信api发送短信
            log.info("code={}",code);
            //4.把验证码存入到session中
            session.setAttribute(phone,code);
            return R.success("验证码发送成功!!!");
        }
        return R.error("验证码发送失败!!!");
    }

    /**
     * 用户手机号登录
     * @param userDto
     * @param request
     * @return
     */
    @PostMapping("/phoneLogin")
    public R<User> phoneLogin(@RequestBody UserDto userDto,HttpServletRequest request) {
        //1.获取用户输入的手机号
        String phone = userDto.getPhone();
        AssertUtils.hasText(phone, "手机号不能为空!!!");
        //2.获取用户输入的验证码
        String code = userDto.getCode();
        AssertUtils.hasText(code, "验证码不能为空!!!");
        //3.从session里面获取验证码
        String phoneCode = (String) request.getSession().getAttribute(phone);
        //4.比对验证码
        if (phoneCode !=null && phoneCode.equals(code)) {
            //5.如果是新用户,则需要保存到数据库里面
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
            if (user == null) {
                return R.error("该手机号未注册,请先注册后再登录!!!");
            }
            request.getSession().setAttribute("user",user.getId());
            //存到日志里面
            Log log = new Log();
            log.setLoginTime(LocalDateTime.now());
            String ip = MyUtils.getIpAddr(request);
            log.setIp(ip);
            log.setIpAddress("四川省成都市");
            log.setLoginWay("验证码登录");
            log.setOperator(phone);
            logService.save(log);
            return R.success(user);
        }
        return R.error("验证码输入有误,请重新输入!!!");
    }

    /**
     * 用户密码登录
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody User user, HttpServletRequest request) {
        //1.获取用户输入的手机号
        String phone = user.getPhone();
        AssertUtils.hasText(phone, "手机号不能为空!!!");
        //2.获取用户输入的密码
        String password = user.getPassword();
        AssertUtils.hasText(password, "密码不能为空!!!");
        //3.创建查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        wrapper.eq(User::getPassword,password);
        User one = userService.getOne(wrapper);
        //4.判断用户是否为null
        if (one ==null) {
            return R.error("用户名或密码错误!!!");
        }
        //5.登录成功
        request.getSession().setAttribute("user", user.getId());
        //6.存到日志里面
        Log log = new Log();
        log.setLoginTime(LocalDateTime.now());
        String ip = MyUtils.getIpAddr(request);
        log.setIp(ip);
        log.setIpAddress("四川省成都市");
        log.setLoginWay("密码登录");
        log.setOperator(phone);
        logService.save(log);
        return R.success(user);
    }


    /**
     * 用户登出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清楚session里面的用户id
        request.getSession().removeAttribute("user");
        return R.success("用户退出成功!!!");
    }

    /**
     * 用户个人资料修改
     * @param user
     * @return
     */
    @PutMapping("/update")
    public R<String> updateUserInfo(@RequestBody User user) {
        userService.updateById(user);
        return R.success("用户信息更新成功!!!");
    }

    /**
     * 用户个人信息展示
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public R<User> getUserInfo(@PathVariable Long userId) {
        User user = userService.getById(userId);
        return R.success(user);
    }


    @PostMapping("/lottery")
    public R<String> lottery(@RequestBody User user,HttpSession session) {
        //1.判断用户信息是否完善
        boolean r= userService.isFinishUserInfo(user);
        //2.没有完善抛异常
        if (!r) {
            return R.error("个人信息未完善,无法抽奖!!!");
        }else {
            //3.判断用户今日是否抽奖,没有抽奖才可以抽
            String label = (String) session.getAttribute("lottery");
            if (label ==null) {
                //4.计算抽奖次数
                Integer hobbyCount = userService.selectHobbyCount(user.getId());
                double lotteryCount = Math.floor(hobbyCount/2);
                Integer totalCount =0;
                for (int i = 0; i <lotteryCount ; i++) {
                    //5.开始抽奖
                    Integer count = LotteryUtils.startLottery();
                    log.info("第{}次抽奖获得的积分为: {}",i+1,count);
                    totalCount += count;
                }
                //6.将获得的积分更新到用户表中
                user.setCount(user.getCount()+totalCount);
                userService.updateById(user);
                session.setAttribute("lottery",user.getId());
                //设置session的过期时间为当天晚上23点59分59秒
                Date lastTime = TimeUtil.getLastTime(new Date());
                Long second = TimeUtil.secondToNextDay(new Date(), lastTime);
                session.setMaxInactiveInterval(Math.toIntExact(second));
                log.info("抽奖获得的总积分为: {}",totalCount);
                return R.success("抽奖成功!!!");
            }else {
                return R.error("用户今日已经抽奖,请明天再试!!!");
            }
        }
    }

    @PostMapping("/consumeCount")
    public R<String> consumeCount(@RequestBody User user) {
        //1.获取用户积分
        Integer count = user.getCount();
        //2.判断积分是否大于0
        if (count>0) {
            //4.大于0就兑换
            user.setCount(count-1);
            userService.updateById(user);
            return R.success("奖励兑换成功!!!");
        }
        //3.如果为0就提示积分不足无法抽奖
        return R.error("积分不足,无法兑换奖励!!!");
    }

}
